package 并发包CountDownLatch;

import java.util.concurrent.CountDownLatch;

/**
 A线程先输出A，等B线程输出B后，A线程再输出C
 */
public class CountDownLatchDemo {
    public static void main(String[] args) {

//        设置计数器值为1
        CountDownLatch countDownLatch = new CountDownLatch(1);

        new ThreadA(countDownLatch,"线程A").start();
        new ThreadB(countDownLatch,"线程B").start();


    }
}

class ThreadA extends Thread {
    private CountDownLatch countDownLatch;

    public ThreadA(CountDownLatch countDownLatch,String name) {
        super(name);
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println("A");
        try {
//            让当前线程等待
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("C");
    }
}

class ThreadB extends Thread {
    private CountDownLatch countDownLatch;

    public ThreadB(CountDownLatch countDownLatch,String name) {
        super(name);
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run() {
        System.out.println("B");
//        让countDownLatch的计数器减1，减到0后，其他线程开始执行
//        如果计数器初始设定是2，这里则要countDown两次，否则其他线程就一直不执行
        countDownLatch.countDown();
    }
}